/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.aop;

import cn.easyplatform.aop.interceptor.AbstractMethodInterceptor;
import cn.easyplatform.lang.Lang;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.IRequestMessage;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class ServiceInterceptor extends AbstractMethodInterceptor {

    private Method getCurrent = null;

    private Method getAttribute = null;


    public ServiceInterceptor() {
        try {
            Class clazz = Class.forName("org.zkoss.zk.ui.Sessions");
            getCurrent = clazz.getMethod("getCurrent");
            clazz = Class.forName("org.zkoss.zk.ui.Session");
            getAttribute = clazz.getMethod("getAttribute", String.class);
        } catch (Exception e) {
            throw Lang.wrapThrow(e);
        }
    }

    @Override
    public boolean beforeInvoke(Object obj, Method method, Object... args) {
        IRequestMessage<?> req = (IRequestMessage<?>) args[0];
        if (req.getSessionId() == null && !(method.getName().equals("call") && obj.getClass().getName().contains("ApiService"))) {
            try {
                Object session = getCurrent.invoke(null);
                if (session != null)
                    req.setSessionId((Serializable) getAttribute.invoke(session, Constants.SESSION_ID));
            } catch (Exception e) {
                throw Lang.wrapThrow(e);
            }
        }
        return true;
    }

    @Override
    public Object afterInvoke(Object obj, Object returnObj, Method method,
                              Object... args) {
        return returnObj;
    }

    @Override
    public Object whenException(Exception e, Object obj, Method method,
                                Object... args) {
        return null;
    }

    @Override
    public Object whenError(Throwable e, Object obj, Method method,
                            Object... args) {
        return null;
    }

}
